package com.luca.system.service.impl;

import com.luca.common.constant.Constants;
import com.luca.common.core.domain.model.LoginUser;
import com.luca.common.core.redis.RedisUtil;
import com.luca.common.utils.StringUtils;
import com.luca.system.domain.SysUserOnline;
import com.luca.system.service.ISysUserOnlineService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 在线用户 服务层处理
 *
 * @author luca
 */
@Service
public class SysUserOnlineServiceImpl implements ISysUserOnlineService {

    @Override
    public List<SysUserOnline> selectOnlineUsers(String userName, String ipaddr) {
        var userOnlineList = new ArrayList<SysUserOnline>();
        Collection<String> keys = RedisUtil.redisTemplate.keys(Constants.LOGIN_TOKEN_KEY + "*");
        keys.forEach(one -> {
            LoginUser user = (LoginUser) RedisUtil.valueOperations.get(one);
            if (StringUtils.isNotEmpty(userName) && StringUtils.isNotEmpty(ipaddr)) {
                if (StringUtils.equals(userName, user.getUsername()) && StringUtils.equals(ipaddr, user.getIpaddr())) {
                    userOnlineList.add(processSysUserOnline(user));
                }
            } else if (StringUtils.isNotEmpty(ipaddr)) {
                if (StringUtils.equals(ipaddr, user.getIpaddr())) {
                    userOnlineList.add(processSysUserOnline(user));
                }
            } else if (StringUtils.isNotEmpty(userName)) {
                if (StringUtils.equals(userName, user.getUsername())) {
                    userOnlineList.add(processSysUserOnline(user));
                }
            } else {
                userOnlineList.add(processSysUserOnline(user));
            }

        });
        return userOnlineList;
    }

    @Override
    public void forceLogout(String tokenId) {
        RedisUtil.redisTemplate.delete(Constants.LOGIN_TOKEN_KEY + tokenId);
    }

    private SysUserOnline processSysUserOnline(LoginUser user) {
        return new SysUserOnline(user.getToken(), user.getUser().getDeptName(), user.getUsername(), user.getIpaddr(), user.getLoginLocation(), user.getBrowser(), user.getOs(), user.getLoginTime());
    }

}
